package com.xmall.auth.timer;

import cn.hutool.core.date.DateUtil;
import com.xmall.auth.service.remote.SysDictServiceFeign;
import com.xmall.define.base.Result;
import com.xmall.define.dto.sys.DictDto;
import com.xmall.timer.handler.ITimerTaskHandler;
import com.xmall.timer.manager.TimerTaskManager;
import com.xmall.utils.DictUtils;
import com.xmall.utils.XmallUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 刷新字典数据
 */
@Slf4j
@Component
public class RefreshDictDataTimerTask implements ITimerTaskHandler {

    @Resource
    private SysDictServiceFeign sysServiceFeign;

    @Resource
    private TimerTaskManager timerTaskManager;

    @Override
    public String key() {
        return "refreshDictDataTimerTask";
    }

    @Override
    public String name() {
        return "刷新字典数据";
    }

    @Override
    public String desc() {
        return "刷新字典数据（执行成功即退出）";
    }

    @Override
    public String cron() {
        return "0 0/1 * * * ?";
    }

    @Override
    public void execute() {
        try {
            log.info("RefreshDictDataTimerTask: {}", DateUtil.formatDateTime(new Date()));
            Result<List<DictDto>> result = sysServiceFeign.dictList();
            XmallUtils.checkRemoteResult(result);
            result.getData().forEach(dictDto -> DictUtils.updateDict(dictDto));

            // 执行成功停止定时任务
            timerTaskManager.stopTask(this.key());
        }catch (Exception e) {
            log.error("RefreshDictDataTimerTask error: {}", e.getMessage());
        }
    }

    @Override
    public Class type() {
        return RefreshDictDataTimerTask.class;
    }
}
